<template>
  <div class="ivrNodeQueueDeal">
    <ul class="tab">
      <li class="tab-item" :class="[active === 1 ? 'tab-item-active' : '']" @click="tabChange(1)">基本信息</li>
      <li class="tab-item" :class="[active === 2 ? 'tab-item-active' : '']" @click="tabChange(2)"  v-show="!isNewConfig">座席分配</li>
      <li class="tab-item" :class="[active === 3 ? 'tab-item-active' : '']" @click="tabChange(3)" v-show="!isNewConfig">时长</li>
      <li class="tab-item" :class="[active === 4 ? 'tab-item-active' : '']" @click="tabChange(4)" v-show="!isNewConfig">流转</li>
    </ul>
    <div class="form_box" v-loading="loading">
      <el-form :model="skillInfoForm" label-position="top" :rules="rules" ref="skillInfoForm" label-width="100px">
        <div class="cont" v-show="active === 1">
        <p class="prompt">
          温馨提示：1、轮流：按座席当前的登录顺序依次振铃，但座席刷新系统可能会导致重置登录顺序（注：如希望刷新系统不重置登录顺序，可联系客服进行配置）。2、随机：随机选择当前技能组登录状态的座席进行振铃。3、距上次接听最久：当前技能组座席中本次登录距离上次接听时间最久的一个座席。（注：若所有座席都没有接听过电话，当电话进线时会优先分配给最后登录的坐席）
          </br><span v-if="isNewConfig">4.已分配座席内的输入框为优先级的设定，技能组中的座席按照优先级接听电话，数字小的优先接听。优先级相同按预先设置的"座席分配策略"选择接通来电的座席。</span>
        </p>
          <div class="skill-group-item">
            <p>PBX</p>
            <el-select size="mini" placeholder="请选择" v-model="skillInfoForm.PBX" :disabled="!!form.Exten" @change="PBXchange">
              <el-option
                v-for="item in pbxs"
                :label="item.NickName + ' (' +item.PBX + ')'"
                :value="item.PBX">
              </el-option>
            </el-select>
          </div>
          <div class="skill-group-item">
            <el-form-item label="技能组名称" prop="DisplayName">
              <el-input v-model="skillInfoForm.DisplayName" :maxlength="16"></el-input>
            </el-form-item>
          </div>
          <div v-show="form.Exten" class="skill-group-item">
            <p>技能组号</p>
            <el-input v-model="skillInfoForm.Exten" disabled></el-input>
          </div>
          <div class="skill-group-item">
            <p>座席分配策略</p>
            <el-select size="mini" placeholder="请选择" v-model="skillInfoForm.Strategy">
              <el-option
                label="轮流"
                value="rrmemory">
              </el-option>
              <el-option
                label="随机"
                value="random">
              </el-option>
              <el-option
                v-if="!isAdd && form.Strategy === 'fewestcalls'"
                label="接听最少"
                :disabled="form.Strategy === 'fewestcalls'?true:false"
                value="fewestcalls">
              </el-option>
              <el-option
                label="距上次接听最久"
                value="leastrecent">
              </el-option>
            </el-select>
          </div>
          <AgentAssign v-if="isNewConfig" :forChannelConfig="true" :PBX="PBXForAgent" :checkedAgentsOfChannelConfig="AssignMembersArr" @assign-change="handleAssignChange"></AgentAssign>
          <div class="skill-group-item" v-show="!isNewConfig">
            <p>是否启用报工号</p>
            <el-radio-group v-model="skillInfoForm.SayExten">
              <el-radio class="radio" :label="true">是</el-radio>
              <el-radio class="radio" :label="false">否</el-radio>
            </el-radio-group>
          </div>
          <div v-show="form.Exten && !isNewConfig" class="skill-group-item">
            <p>是否启用报工号后的提示音</p>
            <el-radio-group v-model="skillInfoForm.AgentExtenPoint">
              <el-radio class="radio" :label="true">是</el-radio>
              <el-radio class="radio" :label="false">否</el-radio>
            </el-radio-group>
          </div>
          <div v-show="form.Exten && !isNewConfig" class="skill-group-item">
            <p>等待音乐</p>
            <el-select size="mini" placeholder="请选择" v-model="skillInfoForm.MusicClass">
              <el-option
                label="系统默认"
                value="">
              </el-option>
              <el-option
                v-for="item in waitMusic"
                :label="item.DisplayName"
                :value="item.Filename">
              </el-option>
            </el-select>
          </div>
          <div v-show="form.Exten && !isNewConfig" class="skill-group-item">
            <p>播报排队位置时间间隔
              <questionToolTip tipContent="设置0则不播报，最小为15秒。"></questionToolTip>
            </p>
            <el-form-item prop="SayQueuePosition">
              <el-input v-model.trim="skillInfoForm.SayQueuePosition">
                <template slot="append">秒</template>
              </el-input>
            </el-form-item>
          </div>
          <div v-show="form.Exten && !isNewConfig" class="skill-group-item">
            <p>进入技能组提示音</p>
            <el-select size="mini" placeholder="请选择" v-model="skillInfoForm.Music">
              <el-option
                label="系统默认"
                value="">
              </el-option>
              <el-option
                v-for="item in ivrSoundOptions"
                :label="item.DisplayName"
                :value="item.Filename">
              </el-option>
            </el-select>
          </div>
          <div class="skill-group-item" v-show="!isNewConfig">
            <p>无空闲座席时立即流转</p>
            <el-radio-group v-model="skillInfoForm.JoinEmpty">
              <el-radio class="radio" :label="'1'">是</el-radio>
              <el-radio class="radio" :label="'0'">否</el-radio>
            </el-radio-group>
          </div>
          <br/>
          <h5 style="padding: 16px 0 12px 0;border-top: 1px solid #ccc;">
            来电弹屏
            <questionToolTip style="margin-left: 14px;" tipContent="来电弹屏页支持最多可同时选择3个，其中系统工单页最多只能选1个，对接页可最多选择2个。当对接页选择了值后，来电弹屏时将优先展示对接页。注意：多来电弹屏只对新版云客服生效"></questionToolTip>
          </h5>
          <div class="skill-group-item" v-show="!isNewConfig">
            <p>系统工单页</p>
            <el-select size="mini" placeholder="请选择" v-model="skillInfoForm.KfBussinessTypeId">
              <el-option
                label="--请选择--"
                value="">
              </el-option>
              <el-option
                v-for="item in businessFlowOnly"
                :label="item.name"
                :value="'business_' + item._id">
              </el-option>
            </el-select>
          </div>
          <div class="skill-group-item" v-show="!isNewConfig">
            <p>对接页</p>
            <el-select size="mini" v-model="skillInfoForm.CallinTypeId" multiple placeholder="请选择">
              <el-option
                v-for="item in callUrls"
                :label="item.name"
                :value="'callUrls_' + item._id">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="cont" v-show="active === 2">
          <p class="prompt">温馨提示：1.已分配座席内的输入框为优先级的设定，技能组中的座席按照优先级接听电话，
            数字小的优先接听，优先级相同按预先设置的"座席分配策略"选择接通来电的座席。
            2.修改坐席优先级后需被修改坐席重新登录后才能生效。</p>
          <AgentAssign v-if="isShowAgentAssign && !isNewConfig" :forChannelConfig="true" :PBX="PBXForAgent" :checkedAgentsOfChannelConfig="AssignMembersArr" @assign-change="handleAssignChange"></AgentAssign>
        </div>
        <div class="cont" v-show="active === 3">
          <p class="prompt">温馨提示：等待时长请配成座席振铃时长的倍数。如：等待时长120秒，座席振铃时长30秒，保证每个排队的用户振铃时长都是30秒。</p>
          <div>
            <div style="width: 40%;display: inline-block;margin-right: 30px;">
              <el-form-item label="等待时长" prop="WaitTime">
                <el-input v-model.trim="skillInfoForm.WaitTime" :maxlength="5">
                  <template slot="append">秒</template>
                </el-input>
              </el-form-item>
            </div>
            <div style="width: 40%;display: inline-block;">
              <el-form-item label="座席振铃时长" prop="Timeout">
                <el-input v-model.trim="skillInfoForm.Timeout" :maxlength="5">
                  <template slot="append">秒</template>
                </el-input>
              </el-form-item>
            </div>
          </div>
        </div>
        <div class="cont cont4" v-show="active === 4">
          <div>
            <p>技能组为空时转向</p>
            <el-select size="mini" placeholder="请选择" v-model="skillInfoForm.ToPeerTypeWhenQueueEmpty" @change="ToPeerTypeWhenQueueEmptyChange">
              <el-option
                v-for="item in toPeerTypeArr"
                :label="item.TypeName"
                :value="item.TypeValue">
              </el-option>
            </el-select>
            <el-select size="mini" placeholder="请选择" filterable v-model="skillInfoForm.ToPeerWhenQueueEmpty">
              <el-option
                v-for="item in ToPeerTypeWhenQueueEmptyOptions"
                :label="item.name"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div>
            <p>正在等待时转向</p>
            <el-select size="mini" placeholder="请选择" v-model="skillInfoForm.ToPeerTypeWhenWait" @change="ToPeerTypeWhenWaitChange">
              <el-option
                v-for="item in toPeerTypeArr"
                :label="item.TypeName"
                :value="item.TypeValue">
              </el-option>
            </el-select>
            <el-select size="mini" placeholder="请选择" filterable v-model="skillInfoForm.ToPeerWhenWait">
              <el-option
                v-for="item in ToPeerWhenWaitOptions"
                :label="item.name"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div>
            <p>等待超时转向</p>
            <el-select size="mini" placeholder="请选择" v-model="skillInfoForm.ToPeerTypeWhenWaitTimeout" @change="ToPeerTypeWhenWaitTimeoutChange">
              <el-option
                v-for="item in toPeerTypeArr"
                :label="item.TypeName"
                :value="item.TypeValue">
              </el-option>
            </el-select>
            <el-select size="mini" placeholder="请选择" filterable v-model="skillInfoForm.ToPeerWhenWaitTimeout">
              <el-option
                v-for="item in ToPeerWhenWaitTimeoutOptions"
                :label="item.name"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div>
            <p>通话结束后转向</p>
            <el-select size="mini" placeholder="请选择" v-model="skillInfoForm.ToPeerTypeWhenHanguped" @change="ToPeerTypeWhenHangupedChange">
              <el-option
                v-for="item in toPeerTypeArr"
                :label="item.TypeName"
                :value="item.TypeValue">
              </el-option>
            </el-select>
            <el-select size="mini" placeholder="请选择" filterable v-model="skillInfoForm.ToPeerWhenHanguped">
              <el-option
                v-for="item in ToPeerWhenHangupedOptions"
                :label="item.name"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
      </el-form>
    </div>
    <div class="footer">
      <el-button class='slide-box__button' @click='cancelClick'>
        取消
      </el-button>
      <el-button class='slide-box__button' type="primary" @click="submit">
        保存
      </el-button>
    </div>
  </div>
</template>
<script>
  import AgentAssign from '@/components/public-modules/agent-assign/AgentAssign.vue'
  import { deepClone } from '@/utils/m7Utils.js'
  import {checkform} from '@/utils/validate'
  import questionToolTip from '@/components/ui-modules/questionToolTip/QuestionToolTip.vue'
  export default {
    name: 'ivrNodeQueueDeal',
    data () {
      let checkSayQueuePosition = (rule, value, callback) => {
        if (!value && value !== 0) {
          return callback(new Error('必填'))
        }
        setTimeout(() => {
          if (value < 15 && value > 0 || value < 0) {
            callback(new Error('设置0则不播报，最小为15秒'))
          } else {
            callback()
          }
        }, 100)
      }
      let validate1 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('必填'))
        }else if (value < 1) {
          callback(new Error('最小值为1'))
        } else if (checkform(value, 'Number')) {
          callback(new Error('必须为数字值'))
        } else {
          callback()
        }
      }
      let checkWaitTime = (rule, value, callback) => {
        if (!value && value !== 0) {
          return callback(new Error('必填'))
        }
        if (value < 1) {
          callback(new Error('最小值为1'))
        } else {
          callback()
        }
      }
      return {
        isShowAgentAssign: false,  //   默认不加载选择座席组件  切换到坐席分配在渲染  避免卡顿
        isNewConfig: false, // 是否为新设置
        active: 1,
        PBXForAgent: '',  //  向 座席分配组件里  传的 pbx
        loading: false,
        callUrls: [],
        agents: [],
        pbxs: [],
        businessFlowOnly: [],
        AssignMembersArr: [],
        skillInfoForm: {
          PBX: '',
          Exten: this.form.Exten || '',   //  技能组号
          SayExten: this.form.SayExten || false,  //   是否启用报工号
          KfBussinessTypeId: '',  //   来电弹屏
          CallinTypeId: [],   //  对接弹屏
          MusicClass: '',   //   等待音乐
          Music: '',    //    进入技能组提示音
          DisplayName: this.form.DisplayName || '',    //    技能组名称
          Strategy: this.form.Strategy || 'rrmemory',  //   座席分配策略
          AgentExtenPoint: this.form.AgentExtenPoint || false,   //   是否启用报工号后的提示音
          SayQueuePosition: this.form.SayQueuePosition || 0,  //    播报排队位置时间间隔
          JoinEmpty: this.form.JoinEmpty || '0',  //   无空闲座席时立即流转
          WaitTime: Number(this.form.WaitTime) || 120,  //    等待时长
          Timeout: Number(this.form.Timeout) || 30,   //    座席振铃时长
          MemberToken: this.form.MemberToken || [],    //  分配座席
          ToPeerTypeWhenQueueEmpty: this.form.ToPeerTypeWhenQueueEmpty || 'system',  //  技能组为空时转向
          ToPeerWhenQueueEmpty: this.form.ToPeerWhenQueueEmpty || '0',  //  技能组为空时转向
          ToPeerTypeWhenWait: this.form.ToPeerTypeWhenWait || 'system',  //  正在等待时转向
          ToPeerWhenWait: this.form.ToPeerWhenWait || '0',  //  正在等待时转向
          ToPeerTypeWhenWaitTimeout: this.form.ToPeerTypeWhenWaitTimeout || 'system',  //  等待超时转向
          ToPeerWhenWaitTimeout: this.form.ToPeerWhenWaitTimeout || '0',  //  等待超时转向
          ToPeerTypeWhenHanguped: this.form.ToPeerTypeWhenHanguped || 'system',    //   通话结束后转向
          ToPeerWhenHanguped: this.form.ToPeerWhenHanguped || '0'    //   通话结束后转向
        },
        toPeerTypeArr: [
          {TypeValue: 'system', TypeName: this.$t('configLazyLoad.process.node')},
          {TypeValue: 'ivr_node_queue', TypeName: '技能组'},
          {TypeValue: 'account_user', TypeName: '座席'},
          {TypeValue: 'ivr_node_announcement', TypeName: '播放语音节点'},
          {TypeValue: 'ivr_node_text_announcement', TypeName: '播放文本语音节点'},
          {TypeValue: 'ivr_node_ivr', TypeName: '按键菜单节点'},
          {TypeValue: 'ivr_node_encrypt_md5', TypeName: 'MD5加密节点'},
          {TypeValue: 'ivr_node_validation', TypeName: '采集输入节点'},
          {TypeValue: 'ivr_node_assignment', TypeName: '赋值节点'},
          {TypeValue: 'ivr_node_route', TypeName: '按变量路由节点'},
          {TypeValue: 'ivr_node_ivr_menu', TypeName: '转IVR菜单节点'},
          {TypeValue: 'ivr_node_call_url', TypeName: 'CallUrl节点'},
          {TypeValue: 'ivr_node_date', TypeName: this.$t('configLazyLoad.process.node8')},
          {TypeValue: 'ivr_node_twowaycall', TypeName: '双向回呼节点'},
          {TypeValue: 'ivr_node_asr', TypeName: '语音识别节点'},
          {TypeValue: 'ivr_node_voice_mail', TypeName: '留言节点'},
          {TypeValue: 'ivr_node_room', TypeName: '会议室节点'},
          {TypeValue: 'ivr_node_satisfaction', TypeName: '自定义满意度节点'},
          {TypeValue: 'ivr_node_superDialJobNum', TypeName: '采集工号并拨打节点'},
          {TypeValue: 'ivr_node_extension_peer', TypeName: '自定义节点'}
        ],
        systemPeerTypeArr: [
          {name: '挂机', value: '0'},
          {name: '满意度调查', value: '1'},
          {name: '拨工号', value: '2'}
        ],
        sounds: [],
        ivrSoundOptions: [],
        waitMusic: [],
        ToPeerTypeWhenQueueEmptyOptions: [],
        ToPeerWhenWaitOptions: [],
        ToPeerWhenWaitTimeoutOptions: [],
        ToPeerWhenHangupedOptions: [],
        rules: {
          DisplayName: [
            { required: true, max: 16, message: '必填且不能超过16个字符', trigger: 'blur' }
          ],
          WaitTime: [
            { required: true, validator: validate1, trigger: 'blur' }
          ],
          Timeout: [
            { required: true, validator: validate1, trigger: 'blur' }
          ],
          SayQueuePosition: [
            { required: true, validator: checkSayQueuePosition, trigger: 'blur' }
          ]
        }
      }
    },
    props: {
      form: {
        type: Object,
        default: function () {
          return {}
        }
      },
      isAdd: Boolean
    },
    computed: {
      currentPBX () {
        return this.$store.state.config.callCenter.currentPBX
      }
    },
    watch: {
      form () {
        this.skillInfoForm.PBX = this.form.PBX || this.pbxs[0].PBX
        this.PBXForAgent = this.skillInfoForm.PBX
        this.skillInfoForm.Exten = this.form.Exten || ''
        this.skillInfoForm.SayExten = this.form.SayExten || false
        //      多个来电弹屏 处理
        this.skillInfoForm.CallinTypeId = []
        if (typeof (this.form.KfBussinessTypeId) === 'undefined') {   //  老版来电弹屏设置
          this.skillInfoForm.KfBussinessTypeId = this.form.BussinessTypeId || ''
          if (this.form.BussinessTypeId) {
            let interfaceId = this.form.BussinessTypeId.split('_')[1]
            for (let y = 0; y < this.callUrls.length; y++) {
              if (this.callUrls[y]._id === interfaceId) {
                this.skillInfoForm.KfBussinessTypeId = ''
                this.skillInfoForm.CallinTypeId.push(this.form.BussinessTypeId)
                break
              }
            }
          }
        } else {
          this.skillInfoForm.KfBussinessTypeId = this.form.KfBussinessTypeId || ''
          for (let i = 0; i < this.callUrls.length; i++) {
            for (let j = 0; j < this.form.CallinTypeId.length; j++) {
              if (this.callUrls[i]._id === this.form.CallinTypeId[j].split('_')[1]) {
                this.skillInfoForm.CallinTypeId.push(this.form.CallinTypeId[j])
              }
            }
          }
//          this.skillInfoForm.CallinTypeId = this.form.CallinTypeId
        }
        if (this.form.MusicClass) {
          this.skillInfoForm.MusicClass = this.form.MusicClass.split('.')[1] === 'wav' ? this.form.MusicClass : this.form.MusicClass + '.wav'
        } else {
          this.skillInfoForm.MusicClass = ''
        }
        if (this.form.Music) {
          this.skillInfoForm.Music = this.form.Music.split('.')[1] === 'wav' ? this.form.Music : this.form.Music + '.wav'
        } else {
          this.skillInfoForm.Music = ''
        }
        this.skillInfoForm.DisplayName = this.form.DisplayName || ''
        this.skillInfoForm.Strategy = this.form.Strategy || 'rrmemory'
        this.skillInfoForm.AgentExtenPoint = this.form.AgentExtenPoint || false
        this.skillInfoForm.SayQueuePosition = this.form.SayQueuePosition || 0
        this.skillInfoForm.JoinEmpty = this.form.JoinEmpty || '0'
        this.skillInfoForm.WaitTime = Number(this.form.WaitTime) || 120
        this.skillInfoForm.Timeout = Number(this.form.Timeout) || 30
//        this.skillInfoForm.MemberToken = this.form.MemberToken || []   //   座席
        this.skillInfoForm.ToPeerTypeWhenQueueEmpty = this.form.ToPeerTypeWhenQueueEmpty || 'system'
        this.ToPeerTypeWhenQueueEmptyChange(this.form.ToPeerTypeWhenQueueEmpty)
        this.skillInfoForm.ToPeerTypeWhenWait = this.form.ToPeerTypeWhenWait || 'system'
        this.ToPeerTypeWhenWaitChange(this.form.ToPeerTypeWhenWait)
        this.skillInfoForm.ToPeerTypeWhenWaitTimeout = this.form.ToPeerTypeWhenWaitTimeout || 'system'
        this.ToPeerTypeWhenWaitTimeoutChange(this.form.ToPeerTypeWhenWaitTimeout)
        this.skillInfoForm.ToPeerTypeWhenHanguped = this.form.ToPeerTypeWhenHanguped || 'system'
        this.ToPeerTypeWhenHangupedChange(this.form.ToPeerTypeWhenHanguped)
        this.getAssignMembersArr()
        this.tabChange(1)
        this.refreshSounds()
      }
    },
    methods: {
      PBXchange () {
        this.loading = true
        if (this.form.Exten) {
          this.loading = false
          this.PBXForAgent = this.skillInfoForm.PBX
          return
        }
        let data = {}
        data.Account = this.$store.state.session.account.account
        data.PBX = this.skillInfoForm.PBX
        if (!this.$store.state.session.ivrMap[data.PBX]) {
          this.$store.dispatch('getAllNodesByPbxForSkill', data).then(() => {
            this.loading = false
            this.PBXForAgent = this.skillInfoForm.PBX
          })
        } else {
          this.loading = false
          this.PBXForAgent = this.skillInfoForm.PBX
        }
        this.AssignMembersArr = []
        this.resetSkillInfo()
      },
//      重置技能组 信息
      resetSkillInfo () {
        this.skillInfoForm.ToPeerTypeWhenQueueEmpty = 'system'
        this.skillInfoForm.ToPeerWhenQueueEmpty = '0'
        this.skillInfoForm.ToPeerTypeWhenWait = 'system'
        this.skillInfoForm.ToPeerWhenWait = '0'
        this.skillInfoForm.ToPeerTypeWhenWaitTimeout = 'system'
        this.skillInfoForm.ToPeerWhenWaitTimeout = '0'
        this.skillInfoForm.ToPeerTypeWhenHanguped = 'system'
        this.skillInfoForm.ToPeerWhenHanguped = '0'
      },
      tabChange (val) {
        this.active = val
        if (val === 2) {
          this.isShowAgentAssign = true
        }
      },
//      分配座席回显
      getAssignMembersArr () {
        this.skillInfoForm.MemberToken = []
        if (!this.form.AssignMembers || this.form.AssignMembers.length === 0) {
          this.AssignMembersArr = []
          return
        }
        let agentArr = []
        let agents = this.$store.getters.agents
        this.form.AssignMembers.forEach(one => {
          this.skillInfoForm.MemberToken.push(one.agentID + ':' + one.penalty)  //  先预存技能组 座席的信息  防止不初始化坐席分配组件带来的  数据为空问题
          if (agents[one.agentID]) {
            agentArr.push({_id: agents[one.agentID]._id, displayName: agents[one.agentID].displayName, exten: agents[one.agentID].exten, count: one.penalty})
          }
        })
        let hash = {}
        agentArr = agentArr.reduce(function (item, next) {
          hash[next._id] ? '' : hash[next._id] = true && item.push(next)
          return item
        }, [])
        this.AssignMembersArr = agentArr
      },
      flowOptionsChange (val, options) {
        let toPeerArr = this.$store.state.session.ivrMap[this.skillInfoForm.PBX].data[val]
        if (!val || val === 'system') {
          this.systemPeerTypeArr.forEach(item => {
            options.push({name: item.name, value: item.value})
          })
        } else {
          options.push({name: '--请选择--', value: ''})
          if (toPeerArr) {
            if (val === 'account_user') {
              toPeerArr.forEach(item => {
                options.push({name: item.displayName, value: item._id})
              })
            } else {
              toPeerArr.forEach(item => {
                options.push({name: item.DisplayName, value: item.Exten})
              })
            }
          }
        }
      },
      //  流转  选择框 change
      ToPeerTypeWhenQueueEmptyChange (val) {
        this.ToPeerTypeWhenQueueEmptyOptions = []
        this.flowOptionsChange(val, this.ToPeerTypeWhenQueueEmptyOptions)
        if (val === this.form.ToPeerTypeWhenQueueEmpty) {
          this.skillInfoForm.ToPeerWhenQueueEmpty = this.form.ToPeerWhenQueueEmpty || this.ToPeerTypeWhenQueueEmptyOptions[0].value
        } else {
          this.skillInfoForm.ToPeerWhenQueueEmpty = this.ToPeerTypeWhenQueueEmptyOptions[0].value
        }
      },
      ToPeerTypeWhenWaitChange (val) {
        this.ToPeerWhenWaitOptions = []
        this.flowOptionsChange(val, this.ToPeerWhenWaitOptions)
        if (val === this.form.ToPeerTypeWhenWait) {
          this.skillInfoForm.ToPeerWhenWait = this.form.ToPeerWhenWait || this.ToPeerWhenWaitOptions[0].value
        } else {
          this.skillInfoForm.ToPeerWhenWait = this.ToPeerWhenWaitOptions[0].value
        }
      },
      ToPeerTypeWhenWaitTimeoutChange (val) {
        this.ToPeerWhenWaitTimeoutOptions = []
        this.flowOptionsChange(val, this.ToPeerWhenWaitTimeoutOptions)
        if (val === this.form.ToPeerTypeWhenWaitTimeout) {
          this.skillInfoForm.ToPeerWhenWaitTimeout = this.form.ToPeerWhenWaitTimeout || this.ToPeerWhenWaitTimeoutOptions[0].value
        } else {
          this.skillInfoForm.ToPeerWhenWaitTimeout = this.ToPeerWhenWaitTimeoutOptions[0].value
        }
      },
      ToPeerTypeWhenHangupedChange (val) {
        this.ToPeerWhenHangupedOptions = []
        this.flowOptionsChange(val, this.ToPeerWhenHangupedOptions)
        if (val === this.form.ToPeerTypeWhenHanguped) {
          this.skillInfoForm.ToPeerWhenHanguped = this.form.ToPeerWhenHanguped || this.ToPeerWhenHangupedOptions[0].value
        } else {
          this.skillInfoForm.ToPeerWhenHanguped = this.ToPeerWhenHangupedOptions[0].value
        }
      },
//      分配座席 组件 抛出事件
      handleAssignChange (agentCount) {
        let agentCounts = agentCount
        this.skillInfoForm.MemberToken = []
        agentCounts.forEach(item => {
          this.skillInfoForm.MemberToken.push(item.agent + ':' + item.count)
        })
      },
      /**
       * 添加/修改技能组
       * @param {Object} data
       * @param {String} data.Account 账户id
       * @param {String} data.PBX pbx
       * @param {String} data.action 'add' => 添加，'update' => 修改
       * @param {String} data.State 是否启用（没找到使用的地方，传'enable'）
       * @param {String} data.Type 类型，'normal'
       * @param {String} data.DisplayName 名称
       * @param {String} data.Strategy 'rrmemory'
       * @param {Boolean} data.SayExten 是否启用报工号
       * @param {Boolean} data.AgentExtenPoint 是否启用报工号后的提示音
       * @param {String} data.JoinEmpty 无空闲座席时立刻流转，'1' => 是，'0' => 否
       * @param {String|Number} data.SayQueuePosition 播报排队位置时间间隔，'0' => 不播报
       * @param {String} data.BussinessTypeId 来电弹屏，'business_${工单流程id}'，'callUrls_${来电弹屏id}'
       * @param {String} data.MusicClass 等待语音
       * @param {String} data.Music 进入技能组提示音
       * @param {String|Number} data.WaitTime 等待时长
       * @param {String|Number} data.Timeout 座席振铃时长
       * @param {String} data.ToPeerTypeWhenQueueEmpty 技能组为空时转向类型
       * @param {String} data.ToPeerWhenQueueEmpty 技能组为空时转向
       * @param {String} data.ToPeerTypeWhenWait 正在等待时转向类型
       * @param {String} data.ToPeerWhenWait 正在等待时转向
       * @param {String} data.ToPeerTypeWhenWaitTimeout 等待超时转向类型
       * @param {String} data.ToPeerWhenWaitTimeout 等待超时转向
       * @param {String} data.ToPeerTypeWhenHanguped 通话结束后转向类型
       * @param {String} data.ToPeerWhenHanguped 通话结束后转向
       * @param {String} data.MemberToken 座席分配，['${座席id}:${优先级}']
       * ---- 以下为修改时要另外提供的 ----
       * @param {String} [data._id] 技能组id
       * @param {String} [data.Exten] 技能组号
       */
      submit () {
        if (this.skillInfoForm.CallinTypeId && this.skillInfoForm.CallinTypeId.length > 2) {
          this.$message.error('来电弹屏对接页最多设置2个')
          return false
        }
        this.$refs.skillInfoForm.validate((valid) => {
          if (valid) {
            let MemberToken = deepClone(this.skillInfoForm.MemberToken)
            let data = deepClone(this.skillInfoForm)
            data.MemberToken = JSON.stringify(MemberToken)
            data.Account = this.$store.state.session.account.account
            data.State = 'enable'
            data.Type = 'normal'
            if (!this.form._id) {
              delete data._id
              delete data.Exten
              data.action = 'add'
            } else {
              data.action = 'update'
              data._id = this.form._id
            }
            this.loading = true
            if (!data.Strategy) {
              data.Strategy = 'rrmemory'
            }
            this.$store.dispatch('updateQueueForSkill', data).then(res => {
              this.loading = false
              if (res.success) {
                this.$emit('refresh', data.PBX)
                this.$emit('reload', false)
                this.$message({
                  type: 'success',
                  message: '技能组保存成功!'
                })
                this.queueRefresh()
              } else {
                this.$emit('reload', true)
              }
            })
          } else {
            this.$message.error('技能组信息校验不通过')
          }
        })
      },
      refreshSounds () {
        this.ivrSoundOptions = []
        this.waitMusic = []
        this.sounds = this.$store.state.session.ivrMap[this.skillInfoForm.PBX].data.ivr_sound
        this.sounds.forEach(item => {
          if (item.SoundType === 'normal') {
            this.ivrSoundOptions.push(item)
          } else if (item.SoundType === 'hold') {
            this.waitMusic.push(item)
          }
        })
      },
      cancelClick () {
        this.$emit('cancelClick')
      },
      queueRefresh () {
        let data = {}
        data.Account = this.$store.state.session.account.account
        data.PBX = this.currentPBX
        this.$store.dispatch('queryQueueForSkill', data).then(res => {
          if (res.success) {
            this.$store.commit('SET_IVRMAP_DETAIL', {PBX: this.currentPBX, typeName: 'ivr_node_queue', data: res.list || [], flag: 'data', node: this})
            this.$emit('saveClick')
          }
        })
      }
    },
    components: {
      AgentAssign,
      questionToolTip
    },
    beforeMount () {
      // let routes = this.$route.path.split('/')
      // if (routes[2] === 'newConfig') { // 是新版设置
        // this.isNewConfig = true
      // } else {
        // this.isNewConfig = false
      // }
      this.pbxs = this.$store.state.session.account.pbx
      this.skillInfoForm.PBX = this.form.PBX || this.pbxs[0].PBX
      this.PBXForAgent = this.skillInfoForm.PBX
//        等待音乐   进入技能组提示音
      if (this.form.MusicClass) {
        this.skillInfoForm.MusicClass = this.form.MusicClass.split('.')[1] === 'wav' ? this.form.MusicClass : this.form.MusicClass + '.wav'
      } else {
        this.skillInfoForm.MusicClass = ''
      }
      if (this.form.Music) {
        this.skillInfoForm.Music = this.form.Music.split('.')[1] === 'wav' ? this.form.Music : this.form.Music + '.wav'
      } else {
        this.skillInfoForm.Music = ''
      }
//           流转部分 选择框的数据渲染
      this.ToPeerTypeWhenQueueEmptyOptions = this.systemPeerTypeArr
      this.ToPeerWhenWaitOptions = this.systemPeerTypeArr
      this.ToPeerWhenWaitTimeoutOptions = this.systemPeerTypeArr
      this.ToPeerWhenHangupedOptions = this.systemPeerTypeArr
      this.skillInfoForm.ToPeerTypeWhenQueueEmpty = this.form.ToPeerTypeWhenQueueEmpty || 'system'
      this.ToPeerTypeWhenQueueEmptyChange(this.form.ToPeerTypeWhenQueueEmpty)
      this.skillInfoForm.ToPeerWhenQueueEmpty = this.form.ToPeerWhenQueueEmpty || this.ToPeerTypeWhenQueueEmptyOptions[0].value
      this.skillInfoForm.ToPeerTypeWhenWait = this.form.ToPeerTypeWhenWait || 'system'
      this.ToPeerTypeWhenWaitChange(this.form.ToPeerTypeWhenWait)
      this.skillInfoForm.ToPeerWhenWait = this.form.ToPeerWhenWait || this.ToPeerWhenWaitOptions[0].value
      this.skillInfoForm.ToPeerTypeWhenWaitTimeout = this.form.ToPeerTypeWhenWaitTimeout || 'system'
      this.ToPeerTypeWhenWaitTimeoutChange(this.form.ToPeerTypeWhenWaitTimeout)
      this.skillInfoForm.ToPeerWhenWaitTimeout = this.form.ToPeerWhenWaitTimeout || this.ToPeerWhenWaitTimeoutOptions[0].value
      this.skillInfoForm.ToPeerTypeWhenHanguped = this.form.ToPeerTypeWhenHanguped || 'system'
      this.ToPeerTypeWhenHangupedChange(this.form.ToPeerTypeWhenHanguped)
      this.skillInfoForm.ToPeerWhenHanguped = this.form.ToPeerWhenHanguped || this.ToPeerWhenHangupedOptions[0].value
      let p1 = this.$store.dispatch('getCache', {type: 'callUrls'})
      let p2 = this.$store.dispatch('getCache', {type: 'businessFlowOnly'})
//      let p3 = this.$store.dispatch('getCache', { type: 'agents' })
      Promise.all([p1, p2]).then(([callUrls, businessFlowOnly]) => {
        this.callUrls = callUrls
        this.businessFlowOnly = businessFlowOnly
//        this.agents = agentsData
        this.getAssignMembersArr()  //   分配座席 回显
        this.refreshSounds()   //   刷新等待音乐和提示音的数据源
        //      多个来电弹屏 处理
        this.skillInfoForm.CallinTypeId = []
        if (typeof (this.form.KfBussinessTypeId) === 'undefined') {   //  老版来电弹屏设置
          this.skillInfoForm.KfBussinessTypeId = this.form.BussinessTypeId || ''
          if (this.form.BussinessTypeId) {
            let interfaceId = this.form.BussinessTypeId.split('_')[1]
            for (let y = 0; y < this.callUrls.length; y++) {
              if (this.callUrls[y]._id === interfaceId) {
                this.skillInfoForm.KfBussinessTypeId = ''
                this.skillInfoForm.CallinTypeId.push(this.form.BussinessTypeId)
                break
              }
            }
          }
        } else {   //  新版来电弹屏设置
          this.skillInfoForm.KfBussinessTypeId = this.form.KfBussinessTypeId || ''
          for (let i = 0; i < this.callUrls.length; i++) {
            for (let j = 0; j < this.form.CallinTypeId.length; j++) {
              if (this.callUrls[i]._id === this.form.CallinTypeId[j].split('_')[1]) {
                this.skillInfoForm.CallinTypeId.push(this.form.CallinTypeId[j])
              }
            }
          }
//          this.skillInfoForm.CallinTypeId = this.form.CallinTypeId
        }
      })
    }
  }
</script>
<style lang="stylus">
.ivrNodeQueueDeal
  .assign
    .selecSate
      padding 0!important
      .scResult
        padding-left 0
        .result
          .el-input
            width 50px
</style>
<style lang="stylus" scoped>
  @import "../../../../../../assets/common.styl"
  .ivrNodeQueueDeal
    padding-top 20px
    overflow-y auto
    box-sizing border-box
    padding-bottom 60px
    height 100%
    .skill-group-item
      width 100%
      display inline-block
      p
       margin-bottom 6px
    .el-form-item
      margin 0
    .el-input
      width 100%
    .el-select
      width 100%
    .el-input,.el-select
      width 100%
    .el-radio-group
      margin 5px 0 0 0
    .tab
      height 30px
      text-align center
      .tab-item
        display inline-block
        cursor pointer
        padding-bottom 3px
        border-top 1px solid #E8E8E8
        border-bottom 1px solid #E8E8E8
        border-right 1px solid #E8E8E8
        width 20%
        padding 7px
        box-sizing border-box
      .tab-item:nth-of-type(1)
        border-left 1px solid #E8E8E8
      .tab-item-active
        color white
        background #459AE9
    .cont
      padding-top 20px
      padding-bottom 20px
    .cont4
      .el-select
        width 40%
        margin-right 5%
      p
       margin-bottom 6px
    .cont4 > div
      margin-bottom 20px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 16px
      border-radius 50%
      margin-left 2px
      .iconfont
        font-size 10px
        color $c-main
    .prompt
      color $c-prompt
      margin-bottom 20px
  .form_box
    // max-height calc(100vh - 275px)
    // overflow-y auto
    padding 0 20px 0
    .skill-group-item
      margin-bottom 20px
  .btn_box
    overflow hidden
  .footer
   position absolute
   bottom 0
   left 0
   width 100%
   z-index 30
   background rgba(255,255,255,1)
   box-shadow 0px -2px 4px 0px rgba(5,49,38,0.05)
   border-top 1px solid rgba(232,232,232,1)
   display flex
   justify-content center
   padding 13px 0
   box-sizing border-box
   .slide-box__button
    padding 8px 20px 8px
    box-sizing border-box
</style>
